#include <stdio.h>
#include <stdlib.h>

#include "SDL/SDL.h"
#include <string>
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include "SDL/SDL_mixer.h"

#undef main

//窗口属性
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;

//将要使用的表面
SDL_Surface *image = NULL;
SDL_Surface *screen = NULL;
SDL_Surface *message = NULL;

//将要播放的音乐
Mix_Music *music = NULL;

//将要使用的声效
Mix_Chunk *scratch = NULL;
Mix_Chunk *high = NULL;
Mix_Chunk *med = NULL;
Mix_Chunk *low = NULL;

//将要用到的事件结构体
SDL_Event event;

//将要用到的字体
TTF_Font *font = NULL;

//字体的颜色
SDL_Color textColor = { 255, 255, 255 };

SDL_Surface *load_image( std::string filename )
{
    //临时的空间，用于存储刚刚加载好的图像
    SDL_Surface* loadedImage = NULL;

    //优化后的图像，实际使用的是这个图像
    SDL_Surface* optimizedImage = NULL;

    //加载图像
    loadedImage = IMG_Load(filename.c_str() );

    //如果加载图片没有出错
    if( loadedImage != NULL )
    {
        //创建一个优化了的图像
        optimizedImage = SDL_DisplayFormat( loadedImage );

        //释放临时的图像
        SDL_FreeSurface( loadedImage );
    }

    //如果图像优化成功
    //    if( optimizedImage != NULL )
    //    {
    //        //映射关键色
    //        Uint32 colorkey = SDL_MapRGB( optimizedImage->format, 0, 0xFF, 0xFF );

    //        //将所有颜色为（R 0, G 0xFF, B 0xFF）的像素设为透明。
    //        SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey );
    //    }

    //返回优化后的表面
    return optimizedImage;
}

void apply_surface( int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip = NULL )
{
    //新建一个临时的矩形来保存偏移量
    SDL_Rect offset;

    //将传入的偏移量保存到矩形中
    offset.x = x;
    offset.y = y;
    //执行表面的Blit
    SDL_BlitSurface( source, clip, destination, &offset );
}

bool load_files()
{
    //加载图像
    image = load_image( "../lesson11/background.png" );

    //打开字体
    font = TTF_OpenFont( "../lesson11/Garuda.ttf", 28 );

    //如果加载出错
    if( image == NULL )
    {
        return false;
    }

    //如果字体加载出错
    if( font == NULL )
    {
        return false;
    }

    //加载音乐
    music = Mix_LoadMUS( "../lesson11/beat.wav" );
    //如果加载音乐出了问题

    if( music == NULL )
    {
        return false;
    }

    //加载声效
    scratch = Mix_LoadWAV( "../lesson11/scratch.wav" );
    high = Mix_LoadWAV( "../lesson11/high.wav" );
    med = Mix_LoadWAV( "../lesson11/medium.wav" );
    low = Mix_LoadWAV( "../lesson11/low.wav" );

    //如果加载声效出了问题
    if( ( scratch == NULL ) || ( high == NULL ) || ( med == NULL ) || ( low == NULL ) )
    {
        return false;
    }

    //如果所有图片加载正常
    return true;
}

void clean_up()
{
    //释放图像
    SDL_FreeSurface( image );

    //释放声效
    Mix_FreeChunk( scratch );
    Mix_FreeChunk( high );
    Mix_FreeChunk( med );
    Mix_FreeChunk( low );

    //释放音乐
    Mix_FreeMusic( music );

    //关闭字体
    TTF_CloseFont( font );

    //退出SDL_mixer
    Mix_CloseAudio();

    //退出SDL_ttf
    TTF_Quit();

    //退出SDL
    SDL_Quit();
}

bool init()
{
    //初始化SDL的所有子系统
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
    {
        return false;
    }

    //设置窗口
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //如果设置出错
    if( screen == NULL )
    {
        return false;
    }

    //初始化SDL_ttf
    if( TTF_Init() == -1 )
    {
        return false;
    }

    //初始化SDL_mixer
    if( Mix_OpenAudio( 22050, MIX_DEFAULT_FORMAT, 2, 4096 ) == -1 )
    {
        return false;
    }

    //设置窗口标题
    SDL_WM_SetCaption( "播放声音", NULL );

    //如果所有初始化操作都成功
    return true;
}

int main(int argc, char *argv[])
{
    printf("hello\n");

    //确保程序一直等待quit
    bool quit = false;

    //初始化
    if( init() == false )
    {
        return 1;
    }

    //加载文件
    if( load_files() == false )
    {
        return 1;
    }

    //用白色填充窗口
    SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );

    //将image表面应用到窗口上
    apply_surface( 0, 0, image, screen);

    //渲染文本
    message = TTF_RenderText_Solid( font, "Press 1, 2, 3, or 4 to play a sound effect", textColor );

    //If there was an error in rendering the text
    if( message == NULL )
    {
        return 1;
    }

    //Show the message on the screen
    apply_surface( ( SCREEN_WIDTH - message->w ) / 2, 100, message, screen );

    //Free the message
    SDL_FreeSurface( message );

    //Render the text
    message = TTF_RenderText_Solid( font, "Press 9 to play or pause the music", textColor );

    //If there was an error in rendering the text
    if( message == NULL )
    {
        return 1;
    }

    //Show the message on the screen
    apply_surface( ( SCREEN_WIDTH - message->w ) / 2, 200, message, screen );

    //Free the message
    SDL_FreeSurface( message );

    //Render the text
    message = TTF_RenderText_Solid( font, "Press 0 to stop the music", textColor );

    //If there was an error in rendering the text
    if( message == NULL )
    {
        return 1;
    }

    //Show the message on the screen
    apply_surface( ( SCREEN_WIDTH - message->w ) / 2, 300, message, screen );

    //Free the message
    SDL_FreeSurface( message );

    //当用户还不想退出时
    while( quit == false )
    {
        //当有事件发生时，我们需要处理它们
        while( SDL_PollEvent( &event ) )
        {

            //如果用户点击了窗口右上角的关闭按钮
            if( event.type == SDL_QUIT )
            {
                //退出程序
                quit = true;
            }

            //如果一个按键被按下
            if( event.type == SDL_KEYDOWN )
            {
                //如果数字键“1”被按下
                if( event.key.keysym.sym == SDLK_1 )
                {
                    //播放“挠”的声效
                    if( Mix_PlayChannel( -1, scratch, 0 ) == -1 )
                    {
                        return 1;
                    }
                }
                //如果数字键“2”被按下
                else if( event.key.keysym.sym == SDLK_2 )
                {
                    //播放“重击”的声效
                    if( Mix_PlayChannel( -1, high, 0 ) == -1 )
                    {
                        return 1;
                    }
                }
                //如果数字键“3”被按下
                else if( event.key.keysym.sym == SDLK_3 )
                {
                    //播放“中度击打”的声效
                    if( Mix_PlayChannel( -1, med, 0 ) == -1 )
                    {
                        return 1;
                    }
                }
                //如果数字键“4”被按下
                else if( event.key.keysym.sym == SDLK_4 )
                {
                    //播放“轻击”的声效
                    if( Mix_PlayChannel( -1, low, 0 ) == -1 )
                    {
                        return 1;
                    }
                }
                //如果数字键“9”被按下
                else if( event.key.keysym.sym == SDLK_9 )
                {
                    //如果没有音乐在播放
                    if( Mix_PlayingMusic() == 0 )
                    {
                        //播放音乐
                        if( Mix_PlayMusic( music, -1 ) == -1 )
                        {
                            return 1;
                        }
                    }
                    //如果音乐已进入播放状态
                    else
                    {
                        //如果音乐被暂停了
                        if( Mix_PausedMusic() == 1 )
                        {
                            //恢复播放
                            Mix_ResumeMusic();
                        }
                        //如果音乐正在播放
                        else
                        {
                            //暂停音乐
                            Mix_PauseMusic();
                        }
                    }
                }
                //如果数字键“0”被按下
                else if( event.key.keysym.sym == SDLK_0 )
                {
                    //停止音乐
                    Mix_HaltMusic();
                }
            }

        }

        //更新窗口
        if( SDL_Flip( screen ) == -1 )
        {
            return 1;
        }
        SDL_Delay(10);
    }

    //清理表面并退出SDL
    clean_up();

    return 0;
}
